#include "epoll_loop.h"
#include "task.h"
#include "timer_loop.h"
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <iostream>

static void disable_cano() {
  termios tio;
  tcgetattr(STDIN_FILENO, &tio);
  tio.c_lflag &= ~(ICANON | ECHO);
  tcsetattr(STDIN_FILENO, TCSANOW, &tio);
}

co_async::TimerLoop timer_loop;
co_async::EpollLoop epoll_loop;

using namespace std::chrono_literals;

co_async::Task<> async_main() {

  int file = co_async::check_error(open("/dev/stdin", O_RDONLY | O_NONBLOCK));
  while (true) {
    auto s = co_await co_async::time_limit(
        timer_loop, co_async::read_string(&epoll_loop, file), 1s);
    if (s) {
      std::cout << "读到了" << *s << std::endl;
      if ((*s) == "q") {
        break;
      }
    } else {
      std::cout << "读到了null" << std::endl;
    }
  }
}

int main() {
  disable_cano();
  auto t = async_main();
  t.get_handle().resume();
  while (!t.get_handle().done()) {
    auto time_out = timer_loop.run();
    epoll_loop.run_once(time_out);
  }
}